﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tools.Client.Library.Cache
{
    public class Client
    {
        private string Path = System.Windows.Forms.Application.StartupPath + "/caches/";

        private static readonly Lazy<Client> lazy =
           new Lazy<Client>(() => new Client());
        public static Client Instance { get { return lazy.Value; } }
        private Client() {
            if (!Directory.Exists(Path))
            {
                Directory.CreateDirectory(Path);
            }
        }

        public void set(string Key, string Value)
        {
            string FileName = this.GetFileName(Key);
            byte[] myByte = System.Text.Encoding.UTF8.GetBytes(this.EncryptKey(Value));
            using (FileStream fsWrite = new FileStream(FileName, FileMode.Create))
            {
                fsWrite.Write(myByte, 0, myByte.Length);
            };
        }

        public string get(string Key)
        {
            string FileName = this.GetFileName(Key);

            string myStr = "";
            try
            {
                using (FileStream fsRead = new FileStream(FileName, FileMode.Open))
                {
                    int fsLen = (int)fsRead.Length;
                    byte[] heByte = new byte[fsLen];
                    int r = fsRead.Read(heByte, 0, heByte.Length);
                    myStr = System.Text.Encoding.UTF8.GetString(heByte);
                    myStr = this.DecryptKey(myStr);
                }
            }
            catch
            {
                throw new MissingFieldException();
            }

            return myStr;
        }


        protected string GetFileName(string Key)
        {
            return Path + Key + ".db";
        }

        protected string DecryptKey(string key)
        {
            return key;
        }

        protected string EncryptKey(string key)
        {
            return key;
        }
    }
}
